package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.uu.utils.uuUtils;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.view.RoundedImageView;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.alipay.Result;
import com.hemaapp.yjnh.bean.AlipayTrade;
import com.hemaapp.yjnh.bean.ClientInfor;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.Order;
import com.hemaapp.yjnh.bean.Order.BillChild;
import com.hemaapp.yjnh.bean.UnionTrade;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.WeixinTrade;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.BaseButtonDialog;
import com.hemaapp.yjnh.view.PayPasswordDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 支付之前未支付的订单
 * @author GuiyouZhang
 */
public class PayActivity extends BaseActivity {

    private final static int REQUEST_INVOICE = 0x03;//发票信息

    IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);//微信
    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_right_btn)
    Button titleRightBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_client_info)
    TextView tvClientInfo;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.layout_blogs)
    LinearLayout layoutBlogs;
    @Bind(R.id.tv_freight)
    TextView tvFreight;
    @Bind(R.id.tv_buy_count)
    TextView tvBuyCount;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.tv_coupons_info1)
    TextView tvCouponsInfo1;
    @Bind(R.id.tv_coupons_info2)
    TextView tvCouponsInfo2;
    @Bind(R.id.tv_coupons_info3)
    TextView tvCouponsInfo3;
    @Bind(R.id.ckbx_stamp)
    CheckBox ckbxStamp;
    @Bind(R.id.layout_food_stamp)
    LinearLayout layoutFoodStamp;
    @Bind(R.id.line_invoice)
    View lineInvoice;
    @Bind(R.id.layout_invoice)
    LinearLayout layoutInvoice;
    @Bind(R.id.tv_invoice)
    TextView tvInvoice;
    @Bind(R.id.tv_balance)
    TextView tvBalance;
//    @Bind(R.id.rbtn_friend)
//    RadioButton rbtnFriend;
    @Bind(R.id.rbtn_balance)
    RadioButton rbtnBalance;
    @Bind(R.id.rbtn_alipay)
    RadioButton rbtnAlipay;
    @Bind(R.id.rbtn_union)
    RadioButton rbtnUnion;
    @Bind(R.id.rbtn_wechat)
    RadioButton rbtnWechat;

    private ArrayList<RadioButton> rbtns = new ArrayList<RadioButton>();// 存储5中支付方式的RadioButton
    private Order order;//支付之前未支付订单时使用
    private User user;
    private ClientInfor infor;//账户信息 	包含了粮票和账户余额等信息
    private String friendNum;//代付人
    private String orderType;// 订单类型	1:普通订单 2:定制订单 3:走走订单 4:代付订单
    private Double freight = 0.0;//运费
    //粮票相关变量
    private Double totalFee = 0.0;//总费用,不适用粮票，且包含运费
    private Integer buycount = 0;//总数量
    private double mAvailStamps = 0.0;//当前账户可用粮票数
    private double mNeedStamps = 0.0;//粮票充足情况下和现金一起支付的粮票数量
    private double mFinalCoupons = 0.0;//最终和现金一起支付的粮票数量
    private double cashFee = 0.0;//最终使用的现金部分
    private String memo = "无";//订单备注	若无，则固定传"无"
    DecimalFormat df = new DecimalFormat("#.00");//保留两位小数
    private String zouzouDate;//走走预约日期
    private String zouzouName;//走走预约人姓名
    private String zouzouID;//走走预约人身份证
    private String zouzouMobile;//走走预约人联系方式
    //发票信息
    private int invoice_type = 3;//发票类型：1纸质发票，2电子发票，3无发票
    private String invoice_head = "无";//发票抬头
    private String invoice_email = "无";//电子发票的邮箱地址
    private String invoice_content = "无";//发票内容

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_pay);
        ButterKnife.bind(this);
        user = BaseApplication.getInstance().getUser();
        super.onCreate(savedInstanceState);
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);
        init();
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        order = (Order) mIntent.getSerializableExtra("order");
        orderType = order.getKeytype();
    }

    @Override
    protected void setListener() {
        titleText.setText("支付订单");
        tvInvoice.setText("不开发票");
        //选择粮票
        ckbxStamp.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //检查粮票
                    if (mAvailStamps >= mNeedStamps) {
                        mFinalCoupons = mNeedStamps;
                    } else {//如果可用粮票不够支付这两种粮票支付方式
                        mFinalCoupons = mAvailStamps;//可用粮票部分全部用于支付现金部分的粮票
                    }
                    cashFee = totalFee - mFinalCoupons;
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append(mFinalCoupons + "粮票，还需支付¥" + uuUtils.formatAfterDot2(totalFee - mFinalCoupons+""));
                } else {
                    mFinalCoupons = 0.0;
                    cashFee = totalFee;
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(totalFee+""));
                }
            }
        });
    }

    @Override
    protected void onResume() {
        String weixinpay = XtomSharedPreferencesUtil.get(mContext, "weixinpay");
        if (weixinpay != null && (weixinpay.equals("1"))) {//说明是从微信支付完成后返回
            XtomSharedPreferencesUtil.save(mContext, "weixinpay", "0");
            String status = XtomSharedPreferencesUtil.get(mContext, "status");
            if ("-1".equals(status)) {  //支付失败
                showTextDialog("支付失败!");
            } else if ("-2".equals(status)) { //支付取消
                showTextDialog("您取消了支付!");
            } else {
                showTextDialog("支付成功");
                setResult(RESULT_OK);
                if (invoice_type != 3) {
                    getNetWorker().saveInvoice(user.getToken(), "0", order.getId(),
                            invoice_type + "", invoice_head, cashFee + "", invoice_email, invoice_content);
                }else
                    toNextPage();
            }
        }
        super.onResume();
    }

    @Override
    protected boolean onKeyBack() {
        finish();
        return true;
    }

    private void init() {
        rbtns.add(rbtnAlipay);
        rbtns.add(rbtnUnion);
        rbtns.add(rbtnWechat);
        rbtns.add(rbtnBalance);
//        rbtns.add(rbtnFriend);
        freight = Double.parseDouble(uuUtils.formatAfterDot2(order.getShipping_fee()));//总运费
        tvFreight.setText("¥" + freight);
        mNeedStamps = Double.valueOf(uuUtils.formatAfterDot2(order.getScore_fee()));
        //计算总费用
        cashFee = totalFee = Double.parseDouble(uuUtils.formatAfterDot2(order.getTotal_fee()));
        //显示收货地址
        tvClientInfo.setText("收件人:" + order.getConsignee()+"    "+order.getPhone());
        tvAddress.setText(order.getAddress());
        //显示要结算的商品
        setGood();
        if (user != null) {//一定要放在最后，因为上面的操作会计算出需要的总费用
            getNetWorker().clientInfor(user.getToken());
        }
    }

    /**
     * 设置显示商品信息
     */
    private void setGood() {
        if (layoutBlogs.getChildCount() != 0) {
            layoutBlogs.removeAllViews();
        }
        ArrayList<BillChild> childs = order.getChildren();
        for (int i = 0; i < childs.size(); i++) {
            BillChild child = childs.get(i);
            View view = LayoutInflater.from(mContext).inflate(
                    R.layout.layout_goods_info, null);
            ItemViewHolder ivHolder = new ItemViewHolder();
            itemFindView(view, ivHolder);
            setItem(child, view, ivHolder, i, childs.size());
            view.setTag(childs.get(i));
            view.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    BillChild child = (BillChild) v.getTag();
                    Intent itGoods = new Intent(mContext, CmnProductionDetailActivity.class);
                    itGoods.putExtra("blog_id", child.getBlog_id());
                    startActivity(itGoods);
                }
            });
        }
        String type = BaseUtil.transNull(childs.get(0).getType());
        if (isNull(type) || type.equals("1")) {
            lineInvoice.setVisibility(View.GONE);
            layoutInvoice.setVisibility(View.GONE);
        }else {
            lineInvoice.setVisibility(View.VISIBLE);
            layoutInvoice.setVisibility(View.VISIBLE);
        }
        tvBuyCount.setText("共" + buycount + "件商品");
        tvTotalFee.setText("共需：¥" + totalFee);
        tvCouponsInfo1.setText("可使用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo1, R.drawable.food_stamp_grey);
        tvCouponsInfo1.append(uuUtils.formatAfterDot2(mNeedStamps+"")+"粮票");
    }

    @OnClick({R.id.title_left_btn, R.id.layout_food_stamp, R.id.layout_invoice, R.id.pay_balance_lay,
            R.id.laytou_alipay, R.id.layout_unipay, R.id.layout_wechat, R.id.tv_pay})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_food_stamp:
                ckbxStamp.setChecked(!ckbxStamp.isChecked());
                break;
            case R.id.layout_invoice:
                Intent itInvoice = new Intent(mContext, InvoiceActivity.class);
                itInvoice.putExtra("type", invoice_type);
                itInvoice.putExtra("head", invoice_head);
                itInvoice.putExtra("email", invoice_email);
                itInvoice.putExtra("content", invoice_content);
                startActivityForResult(itInvoice, REQUEST_INVOICE);
                break;
            case R.id.pay_balance_lay:
                setRbtn(rbtnBalance);
                break;
            case R.id.laytou_alipay:
                setRbtn(rbtnAlipay);
                break;
            case R.id.layout_unipay:
                setRbtn(rbtnUnion);
                break;
            case R.id.layout_wechat:
                setRbtn(rbtnWechat);
                break;
            case R.id.tv_pay:
                if (getPayment() == -1) {//如果没有选择支付方式
                    if (cashFee > 0 || !ckbxStamp.isChecked()) {//非全粮票购买
                        XtomToastUtil.showShortToast(mContext, "请选择支付方式");
                        break;
                    }
                }
                if (rbtnWechat.isChecked() && !msgApi.isWXAppInstalled()) {//如果选择了微信支付，那么先判断是否安装了微信
                    XtomToastUtil.showShortToast(mContext,"未检测到您手机的微信");
                    break;
                }
                if (getPayment() == 4 || mFinalCoupons > 0.0)
                    showPasDialog();
                else
                    toTrade("");
                break;
        }
    }
    public int getPayment() {
        if (rbtnAlipay.isChecked()) {
            return 1;
        }
        if (rbtnUnion.isChecked()) {
            return 2;
        }
        if (rbtnWechat.isChecked()) {
            return 3;
        }
        if (rbtnBalance.isChecked()) {
            return 4;
        }
//        if (rbtnFriend.isChecked()) {
//            return 5;
//        }
        return -1;//没有选择支付方式：可能是全粮票
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
            case ACCOUNT_GET:
            case ORDER_SAVEOPERATE:
            case INVOICE_SAVE:
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
            case ADDRESS_LIST:
                showProgressDialog("请稍候");
                break;
            default:
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
            case ACCOUNT_GET:
            case FEEACCOUNT_REMOVE:
            case ORDER_SAVEOPERATE:
            case SCORE_REMOVE:
            case INVOICE_SAVE:
            case ADDRESS_LIST:
                cancelProgressDialog();
                break;
            default:
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ACCOUNT_GET:
                HemaArrayResult<ClientInfor> cResult = (HemaArrayResult<ClientInfor>) baseResult;
                infor = cResult.getObjects().get(0);
                tvBalance.setText("（可用¥" + uuUtils.formatAfterDot2(infor.getFeeaccount()) + ")");
                if (!isNull(infor.getScore())) {
                    mAvailStamps = Double.parseDouble(infor.getScore());
                    tvCouponsInfo2.setText("该商品可用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
                    tvCouponsInfo2.append(mNeedStamps + "粮票 (可用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
                    tvCouponsInfo2.append(df.format(mAvailStamps)+"粮票)");
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(totalFee+""));
                }
                break;
            case ALIPAY:
                HemaArrayResult<AlipayTrade> aResult = (HemaArrayResult<AlipayTrade>) baseResult;
                AlipayTrade trade = aResult.getObjects().get(0);
                String orderInfo = trade.getAlipaysign();
                new AlipayThread(orderInfo).start();
                break;
            case UNIONPAY:
                HemaArrayResult<UnionTrade> uResult = (HemaArrayResult<UnionTrade>) baseResult;
                UnionTrade uTrade = uResult.getObjects().get(0);
                String uInfo = uTrade.getTn();
//                UPPayAssistEx.startPayByJAR(this, com.unionpay.uppay.PayActivity.class, null, null,
//                        uInfo, BaseConfig.UNIONPAY_TESTMODE);
                UPPayAssistEx.startPay (this, null, null, uInfo, BaseConfig.UNIONPAY_TESTMODE);
                break;
            case WEIXINPAY:
                HemaArrayResult<WeixinTrade> wResult = (HemaArrayResult<WeixinTrade>) baseResult;
                WeixinTrade wTrade = wResult.getObjects().get(0);
                goWeixin(wTrade);
                break;
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
                showTextDialog("支付成功");
                if (invoice_type != 3) {
                    getNetWorker().saveInvoice(user.getToken(), "0", order.getId(),
                            invoice_type + "", invoice_head, cashFee + "", invoice_email, invoice_content);
                } else {
                    toNextPage();
                }
                break;
            case INVOICE_SAVE:
                XtomToastUtil.showShortToast(mContext, "发票保存成功");
                toNextPage();
                break;
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if ("14".equals(keytype)) {//同意代付
                    setResult(RESULT_OK);
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    finish();
                }
        }
    }

    private void goWeixin(WeixinTrade trade) {
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);

        PayReq request = new PayReq();
        request.appId = trade.getAppid();
        request.partnerId = trade.getPartnerid();
        request.prepayId = trade.getPrepayid();
        request.packageValue = trade.getPackageValue();
        request.nonceStr = trade.getNoncestr();
        request.timeStamp = trade.getTimestamp();
        request.sign = trade.getSign();
        msgApi.sendReq(request);
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ORDER_ADD:
            case ACCOUNT_GET:
                showTextDialog(baseResult.getMsg());
                break;
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
                XtomToastUtil.showShortToast(mContext, "支付失败," + baseResult.getMsg());
//                toNextPage(false);
                break;
            case INVOICE_SAVE:
                XtomToastUtil.showShortToast(mContext, "发票保存失败，" + baseResult.getMsg());
                toNextPage();
                break;
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if ("14".equals(keytype)) {//同意代付
                    XtomToastUtil.showShortToast(mContext, "同意代付失败，" + baseResult.getMsg());
                    setResult(RESULT_OK);
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    finish();
                }
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation info = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (info) {
            case ACCOUNT_GET:
                showTextDialog("获取账户信息失败");
                break;
            case ORDER_ADD:
                showTextDialog("订单生成失败");
                break;
            case FEEACCOUNT_REMOVE:
            case SCORE_REMOVE:
            case ALIPAY:
            case UNIONPAY:
            case WEIXINPAY:
                XtomToastUtil.showShortToast(mContext, "支付失败,");
                break;
            case ORDER_SAVEOPERATE:
                String keytype = netTask.getParams().get("keytype");
                if ("14".equals(keytype)) {//同意代付
                    XtomToastUtil.showShortToast(mContext, "同意代付失败");
                }
                break;
            case INVOICE_SAVE:
                XtomToastUtil.showShortToast(mContext, "发票保存失败");
                toNextPage();
                break;
            default:
                break;
        }
    }

    private void setRbtn(RadioButton rbtn) {
        for (RadioButton rb : rbtns) {
            if (rbtn.equals(rb)) {
//                rb.setChecked(true);
                rb.setChecked(!rb.isChecked());
            } else {
                rb.setChecked(false);
            }
        }
    }

    private BaseButtonDialog.OnButtonListener buttonListener =
            new BaseButtonDialog.OnButtonListener() {

                @Override
                public void onRightButtonClick(BaseButtonDialog dialog) {
                    dialog.cancel();
                }

                @Override
                public void onLeftButtonClick(BaseButtonDialog dialog) {

                }
            };

    public void showPasDialog() {
        PayPasswordDialog dialog = new PayPasswordDialog(mContext);
        dialog.setClickListener(new PayPasswordDialog.onPasswordClickListener() {
            @Override
            public void onPasswordConfirm(String password) {
                toTrade(password);
            }

            @Override
            public void onPasswordCancel() {
            }
        });
        dialog.builder().show();
    }

    private void toTrade(String password) {
        if (!ckbxStamp.isChecked()) {//如果没有使用粮票，那么全部用现金支付
            mFinalCoupons = 0.0;
        }
        if (cashFee == 0) {//如果现金部分为0，那么调用全粮票支付
            scoreRemove(password);
            return;
        }
        if (rbtnAlipay.isChecked()) {
            alipayTrade(password);
        }
        if (rbtnUnion.isChecked()) {
            uppayTrade(password);
        }
        if (rbtnWechat.isChecked()) {
            weixinTrade(password);
        }
        if (rbtnBalance.isChecked()) {
            feeaccountRemove(password);
//            if (cashFee > Double.valueOf(infor.getFeeaccount())) { // 余额不足
//                HemaButtonDialog dialog = new HemaButtonDialog(mContext);
//                dialog.setText("抱歉余额不足\n是否去充值？");
//                dialog.setLeftButtonText("取消");
//                dialog.setRightButtonText("充值");
//                dialog.setButtonListener(new OnButtonListener() {
//
//                    @Override
//                    public void onRightButtonClick(HemaButtonDialog dialog) {
//                        dialog.cancel();
//                        Intent it = new Intent(mContext, ChargeMoneyActivity.class);
//                        it.putExtra("type", 1);
//                        mContext.startActivity(it);
//                    }
//
//                    @Override
//                    public void onLeftButtonClick(HemaButtonDialog dialog) {
//                        dialog.cancel();
//                    }
//                });
//                dialog.show();
//            } else {
//                feeaccountRemove(password);
//            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
//            case REQUEST_FRIEND:
//                friendNum = data.getStringExtra("phone");
//                setRbtn(rbtnFriend);
//                break;
            case REQUEST_INVOICE:
                invoice_type = data.getIntExtra("type", 3);
                invoice_head = data.getStringExtra("head");
                invoice_email = data.getStringExtra("email");
                invoice_content = data.getStringExtra("content");
                String info = "";
                if (invoice_type == 1) {
                    info = "纸质发票\n" + invoice_head + "\n" + invoice_content;
                } else if (invoice_type == 2) {
                    info = "电子发票\n" + invoice_head + "\n" + invoice_content;
                } else {
                    info = "不开发票";
                }
                tvInvoice.setText(info);
                break;
            default:
                //银联的支付回调
                if (data == null) {
                    return;
                }
                String msg = "";
            /*
			 * 支付控件返回字符串:success、fail、cancel 分别代表支付成功，支付失败，支付取消
			 */
                String str = data.getExtras().getString("pay_result");
                if (str.equalsIgnoreCase("success")) {
                    msg = "支付成功！";
                    showTextDialog(msg);
                    setResult(RESULT_OK);
                    if (invoice_type != 3) {
                        getNetWorker().saveInvoice(user.getToken(), "0", order.getId(),
                                invoice_type + "", invoice_head, cashFee + "", invoice_email, invoice_content);
                    }else
                        toNextPage();
                } else if (str.equalsIgnoreCase("fail")) {
                    msg = "支付失败！";
                    showTextDialog(msg);
                } else if (str.equalsIgnoreCase("cancel")) {
                    msg = "您取消了支付";
                    showTextDialog(msg);
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 全粮票购买
     *
     * @param password
     */
    private void scoreRemove(String password) {
        if (user != null) {
            getNetWorker().scoreRemove(user.getToken(), "1", order.getId(), mFinalCoupons + "", password);
        }
    }

    //余额购买

    /**
     * 后期设计不需要支付密码，这里的密码可以去掉，也可以随便传一个字符串
     *
     * @param password
     */
    private void feeaccountRemove(String password) {
        getNetWorker().feeaccountRemove(user.getToken(), "1",
                order.getId(), password, cashFee + "", mFinalCoupons + "");
    }

    // 支付宝
    private void alipayTrade(String password) {
        getNetWorker().alipay(user.getToken(), "1", "2", order.getId(), cashFee + "", mFinalCoupons + "", password);
    }

    // 银联
    private void uppayTrade(String password) {
        getNetWorker().unionpay(user.getToken(), "2", "2", order.getId(), cashFee + "", mFinalCoupons + "", password);
    }

    // 微信
    private void weixinTrade(String password) {
        getNetWorker().weixinpay(user.getToken(), "3", "2", order.getId(), cashFee + "", mFinalCoupons + "", password);
    }

    private class AlipayThread extends Thread {
        String orderInfo;
        AlipayHandler alipayHandler;

        public AlipayThread(String orderInfo) {
            this.orderInfo = orderInfo;
            alipayHandler = new AlipayHandler(PayActivity.this);
        }

        @Override
        public void run() {
            // 构造PayTask 对象
            PayTask alipay = new PayTask(PayActivity.this);
            String result = alipay.pay(orderInfo);

            log_i("result = " + result);
            Message msg = new Message();
            msg.obj = result;
            alipayHandler.sendMessage(msg);
        }
    }

    private class AlipayHandler extends Handler {
        PayActivity activity;

        public AlipayHandler(PayActivity activity) {
            this.activity = activity;
        }

        public void handleMessage(Message msg) {
            Result result = new Result((String) msg.obj);
            // activity.showTextDialog(result.getResult());
            int staus = result.getResultStatus();
            switch (staus) {
                case 9000:
                    activity.showTextDialog("支付成功");
                    if (invoice_type != 3) {
                        getNetWorker().saveInvoice(user.getToken(), "0", order.getId(),
                                invoice_type + "", invoice_head, cashFee + "", invoice_email, invoice_content);
                        return;
                    }
                    toNextPage();
                    break;
                default:
                    activity.showTextDialog(result.getResult());
                    break;
            }
        }

        ;
    }

    /**支付成功后
     * 跳转到下一个界面
     */
    private void toNextPage() {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                if (!order.getClient_id().equals(BaseApplication.getInstance().getUser().getId())) {//是别人申请的代付订单
                    getNetWorker().orderSaveoperate(user.getToken(), order.getId(), "14", "无",
                            "无", "无", "无");
                } else {
                    setResult(RESULT_OK);
                    EventBusMsg msg = new EventBusMsg();
                    msg.setType(EventBusConfig.UPDATE_ORDER);
                    EventBus.getDefault().post(msg);
                    finish();
                }
            }
        }, 1000);
    }

    private class ItemViewHolder {
        private CheckBox del_checkbox;
        private RoundedImageView img;
        private TextView name;
        private TextView price;
        private TextView amount;
        private View divView;
    }
    /**
     * 一个订单中的多个商品
     *
     * @param view
     * @param ivHolder
     */
    private void itemFindView(View view, ItemViewHolder ivHolder) {
        ivHolder.del_checkbox = (CheckBox) view.findViewById(R.id.del_checkbox);
        ivHolder.img = (RoundedImageView) view.findViewById(R.id.img);
        ivHolder.name = (TextView) view.findViewById(R.id.goods_name_tv);
        ivHolder.price = (TextView) view.findViewById(R.id.goods_price_tv);
        ivHolder.amount = (TextView) view.findViewById(R.id.goods_amount_tv);
        ivHolder.divView = view.findViewById(R.id.div);
    }

    private void setItem(BillChild child, View view, ItemViewHolder ivHolder
            , int i, int total) {
        ivHolder.del_checkbox.setVisibility(View.GONE);
        ImageUtils.loadSmalImage(mContext, child.getImgurl(), ivHolder.img);
        ivHolder.name.setText(child.getName());
        ivHolder.price.setText(child.getPrice());
        ivHolder.amount.setVisibility(View.VISIBLE);
        if (!isNull(child.getBuycount())) {
            int count = Integer.parseInt(child.getBuycount());
            ivHolder.amount.setText("x" + count);
            buycount += count;
        }
        if (i != total - 1) {
            ivHolder.divView.setVisibility(View.VISIBLE);
        }
        layoutBlogs.addView(view);
    }
}
